﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class InvoiceParse : XForm
    {
        public InvoiceParse()
        {
            InitializeComponent();
        }

        private void InvoiceParse_Load(object sender, EventArgs e)
        {

            btnOku.ItemClick += barButtonItem1_ItemClick;
            btnAktar.ItemClick += btnAktar_ItemClick;

            gleCust.Edit.Assign(RI(Rp.V_Customer));
        }

        void btnAktar_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ExecuteNonQuery("AktarInvoice", di.Serialize(), gleCust.ToInt());
            Notify("Done.");
        }

        DataTable di = new DataTable();
        void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            di = new DataTable("Inv");
            di.Columns.Add("InvDate", typeof(string));
            di.Columns.Add("InvNo", typeof(string));
            di.Columns.Add("FileName", typeof(string));
            di.Columns.Add("Season", typeof(string));
            //di.Columns.Add("Label", typeof(string));
            di.Columns.Add("Modello", typeof(string));
            di.Columns.Add("Art", typeof(string));
            di.Columns.Add("Description", typeof(string));
            di.Columns.Add("Quantity", typeof(int));
            di.Columns.Add("UPrice", typeof(float));

            di.Columns.Add("Ord", typeof(string));  //CC
            di.Columns.Add("Ref", typeof(string));    //CC

            using (OpenFileDialog fdOpen = new OpenFileDialog())
            {
                fdOpen.Filter = "Excel Files (*.xls*;*.csv)|*.xls*;*.csv";
                //fdOpen.Filter = "Excel Files (*.xls*)|*.xls*";
                //fdOpen.Filter = "Excel Files|*.xls*|CSV files|*.csv";
                fdOpen.FilterIndex = 1;
                fdOpen.Multiselect = true;
                if (fdOpen.ShowDialog(AppSession.MainForm) == DialogResult.OK)
                {
                    foreach (string FileName in fdOpen.FileNames)
                        ReadExcel(FileName);

                }

                gridView1.Init(di);
                gridView1.AddSummary();
            }
        }


        public void ReadExcel(string filename)
        {
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(filename);
            System.Data.DataSet dataSet = workbook.GetDataSet(
                SpreadsheetGear.Data.GetDataFlags.NoColumnTypes |
                SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders);

            foreach (DataTable d in dataSet.Tables)
                if (d.TableName.StartsWith("INVOICE"))
                {
                    if (d.Columns.Count > 64)
                    {
                        ShowErrorMessage(filename + " adlı dosyanın " + d.Columns.Count + " sütunu var. Düzeltip tekrar deneyin");
                        break;
                    }

                    string InvDate = string.Empty;
                    string InvNo = string.Empty;

                    for (int i = 0; i < d.Rows.Count; i++)
                        for (int j = 0; j < d.Columns.Count; j++)
                            switch (d.Rows[i][j].ToStr())
                            {
                                case "Inv. Date":
                                case "Invoice Date":

                                    for (int k = j + 1; k < d.Columns.Count; k++)
                                        if (d.Rows[i][k].ToStr() != string.Empty)
                                        {
                                            InvDate = d.Rows[i][k].ToStr();
                                            break;
                                        }
                                    break;

                                case "Invoice Number":
                                case "Inv. No":
                                    for (int k = j + 1; k < d.Columns.Count; k++)
                                        if (d.Rows[i][k].ToStr() != string.Empty)
                                        {
                                            InvNo = d.Rows[i][k].ToStr();
                                            break;
                                        }
                                    break;
                            }

                    int firstrow = 0;
                    int lastrow = 0;
                    string Season = string.Empty;
                    for (int i = 0; i < d.Rows.Count; i++)
                        if (d.Rows[i][0].ToStr().StartsWith("Season"))
                        {
                            Season = d.Rows[i][0].ToStr().Substring(7).Replace(":", string.Empty).Trim();
                            firstrow = i + 1;

                            for (int i2 = firstrow; i2 < d.Rows.Count; i2++)
                                if (d.Rows[i2][0].ToStr() == string.Empty)
                                {
                                    lastrow = i2 - 1;
                                    break;
                                }
                            break;
                        }

                    if (firstrow == 0)
                    {
                        ShowErrorMessage(filename + " adlı dosyanın ilk sütununda season ile başlayan hücre yok; satır başlangıcı anlaşılamadı. Düzeltip tekrar deneyin.");
                        break;
                    }
                    else
                    {
                        for (int i = d.Rows.Count - 1; i >= 0; i--)
                            if (i > lastrow ||
                                i < firstrow)
                                d.Rows.RemoveAt(i);

                        Dictionary<string, int> indexes = new Dictionary<string, int>();

                        foreach (DataRow dr0 in d.Rows)
                        {
                            for (int colIndex = 0; colIndex < d.Columns.Count; colIndex++)
                            {
                                switch (dr0[colIndex].ToString())
                                {
                                    //case "Label": indexes.Add("Label", colIndex); break;
                                    case "Modello": indexes.Add("Modello", colIndex); break;
                                    case "Art":
                                    case "expr2-ita": indexes.Add("Art", colIndex); break;
                                    case "Description": indexes.Add("Description", colIndex); break;
                                    case "Quantity": indexes.Add("Quantity", colIndex); break;
                                    case "U.Price": indexes.Add("UPrice", colIndex); break;
                                }
                            }
                        }

                        foreach (DataRow dr0 in d.Rows)
                        {
                            if (d.Rows.IndexOf(dr0) == 0)
                                continue;

                            DataRow r = di.NewRow();
                            r["FileName"] = filename;
                            r["Season"] = Season;
                            r["InvDate"] = InvDate;
                            r["InvNo"] = InvNo;

                            //if (indexes.ContainsKey("Label"))
                            //    r["Label"] = dr0[indexes["Label"]];
                            if (indexes.ContainsKey("Modello"))
                                r["Modello"] = dr0[indexes["Modello"]];
                            if (indexes.ContainsKey("Art"))
                                r["Art"] = dr0[indexes["Art"]];
                            if (indexes.ContainsKey("Description"))
                                r["Description"] = dr0[indexes["Description"]];
                            if (indexes.ContainsKey("Quantity"))
                                r["Quantity"] = dr0[indexes["Quantity"]].ToInt();
                            if (indexes.ContainsKey("UPrice"))
                                r["UPrice"] = dr0[indexes["UPrice"]].ToDecimal();

                            di.Rows.Add(r);
                        }

                    }
                }

        }
    }
}
